function populateUserInfo() {
    var who = JSON.parse(localStorage.getItem("loggedinUser"));
    var users = JSON.parse(localStorage.getItem("users"));
    //find the person who is logged in
    const user = users.find(u => u.email === who["email"]);

    document.getElementById("nameInput").value = user["name"];
    document.getElementById("schoolInput").value = user["school"];
    document.getElementById("cityInput").value = user["city"];
    document.getElementById("genderInput").value = user["gender"];
    document.getElementById("emailInput").value = user["email"];

    // 显示头像
    const avatar = document.getElementById('avatar');
    avatar.src = user["avatar"] || 'default-avatar.jpg'; // 如果没有头像，显示默认头像
}
populateUserInfo();

function editProfile() {
    document.getElementById('personalInfoFields').disabled = false;
}

function saveProfile() {
    var name = document.getElementById('nameInput').value;
    var school = document.getElementById('schoolInput').value;
    var city = document.getElementById('cityInput').value;
    var gender = document.getElementById('genderInput').value;
    var email = document.getElementById('emailInput').value;

    // 清除之前的错误提示
    document.getElementById('nameError').textContent = '';
    document.getElementById('schoolError').textContent = '';
    document.getElementById('cityError').textContent = '';
    document.getElementById('genderError').textContent = '';
    document.getElementById('emailError').textContent = '';

    // 表单验证
    if (name === '') {
        document.getElementById('nameError').textContent = 'Name is required';
        return;
    }
    if (email === '') {
        document.getElementById('emailError').textContent = 'Email is required';
        return;
    }

    var who = JSON.parse(localStorage.getItem("loggedinUser"));
    var users = JSON.parse(localStorage.getItem("users"));
    const user = users.find(u => u.email === who["email"]);

    user.name = name;
    user.city = city;
    user.school = school;
    user.gender = gender;
    user.email = email;

    // 处理头像
    const avatarInput = document.getElementById('avatarInput');
    const file = avatarInput.files[0];
    if (file) {
        const reader = new FileReader();
        reader.onload = function (e) {
            user.avatar = e.target.result;
            localStorage.setItem("loggedinUser", JSON.stringify(user));
            localStorage.setItem("users", JSON.stringify(users));
        };
        reader.readAsDataURL(file);
    } else {
        localStorage.setItem("loggedinUser", JSON.stringify(user));
        localStorage.setItem("users", JSON.stringify(users));
    }

    document.getElementById('personalInfoFields').disabled = true;
    alert('User Data Saved');
}